<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="1000px" defaultFullscreen>
    <BasicForm @register="registerForm" ref="formRef" >
      <template #subTableSlot>
        <JVxeTable ref="subTableRef" :columns="jvxeSubTableSchema" toolbar resizable asyncRemove rowNumber :dataSource="subTableDataSource">
          <template #tableAction="props">
            <a-divider type="vertical" />
            <Popconfirm title="确定删除吗？" @confirm="onSubTableDeleteRow(props)">
              <a>{{ t('action.delete') }}</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="基础信息" key="codegenFormColumn" :forceRender="true">
        <JVxeTable dragSort sortKey="ordinalPosition" sortBegin=1 keep-source resizable ref="codegenFormColumn" :loading="codegenFormColumnTable.loading"
          :columns="codegenFormColumnTable.columns" :dataSource="codegenFormColumnTable.dataSource" :maxHeight=600
           :rowSelection="true" :toolbar="true">
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="更多信息" key="validateFormColumn" :forceRender="true">
        <JVxeTable keep-source resizable ref="validateFormColumn" :loading="validateFormColumnTable.loading"
          :columns="validateFormColumnTable.columns" :dataSource="validateFormColumnTable.dataSource" :maxHeight=600
           :rowSelection="true" :toolbar="true">
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { useI18n } from '@/hooks/web/useI18n';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
import { JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
import { formSchema, codegenFormColumnColumns,validateFormColumnColumns,jvxeSubTableSchema } from '../CodeGenTable.data';
import { update, codegenFormColumnList,validateFormColumnList } from '../CodeGenTable.api';
// Emits声明
const emit = defineEmits(['register', 'success']);
const { t } = useI18n();
const isUpdate = ref(true);
const codegenFormColumn = ref();
const validateFormColumn = ref();
const refKeys = ref(['codegenFormColumn','validateFormColumn']);
const activeKey = ref('codegenFormColumn');
const subTableRef = ref<JVxeTableInstance>();
const tableRefs = { codegenFormColumn,validateFormColumn };
const subTableDataSource = ref<any[]>([]);
const codegenFormColumnTable = reactive({
  loading: false,
  dataSource: [],
  columns: codegenFormColumnColumns,
});
const validateFormColumnTable = reactive({
  loading: false,
  dataSource: [],
  columns: validateFormColumnColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  subTableDataSource.value = [];
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    subTableDataSource.value = data?.record?.subHeads || [];
    requestSubTableData(codegenFormColumnList, { id: data?.record?.id }, codegenFormColumnTable);
    requestSubTableData(validateFormColumnList, { id: data?.record?.id }, validateFormColumnTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'codegenFormColumn';
  codegenFormColumnTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  console.log("allValues:",allValues)
  return {
    ...main, // 展开
    codegenFormColumnList: allValues.tablesValue[0].tableData,
    validateFormColumnList: allValues.tablesValue[1].tableData,
  };
}

async function onSubTableDeleteRow(props) {
    // 异步调用删除方法
    const res = await subTableRef.value?.removeRows(props.row, true);
    console.log('删除成功~', res);
  }


  
  async function getSubTableData() {
    let subTableDataValid = true;
    let subTableData: Recordable[] = [];
    if (!subTableDataValid) {
      throw { errorFields: [{ name: ['subTables'] }] };
    }
     subTableData = subTableRef.value!.getTableData();
    console.log('获取值:', { subTableData });
    return subTableData;
  }


//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    let tableType = values.tableType;
    if(tableType ==='6'){
      values.subTables = await getSubTableData();
    }
    //提交表单
    await update(values);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped></style>
